package com.weirn.algorithm.linkedlist;

/**
 * Created by yp-tc-2563 on 2018/1/25.
 * 单向链表,非线程安全,没有链表头,第一个元素就是实体元素
 */
public class SinglyLinkedList<E> {

    private Node first;

    public long size;

    public Boolean removeFirst(){
        if(size > 0){
            first = first.getNext ();
            size--;
            return true;
        }
        return false;
    }

    public Boolean addFirst(E e){
        Node newNode = new Node ( e,first );
        first = newNode;
        size++;
        return true;
    }

    public long find(E e){
        Node node = first;
        long index = 0L;
        while(node.getNext () != null){
            if(first.getElement ().equals ( e )){
                index++;
                return index;
            }
        }
        return -1;
    }

    public void displayFisrt(){
        if(this.first == null){
            System.out.println ("empty!");
            return;
        }
        System.out.print(first.element);
        Node next = first.next;
        while(next!= null){
            System.out.print("->" + next.element);
            next = next.next;
        }
        System.out.println();

    }

    public SinglyLinkedList() {
    }

    public SinglyLinkedList(Node first) {
        this.first = first;
    }

    public static void main(String args[]){
        java.util.LinkedList<String> linkedList = new java.util.LinkedList<> (  );
        SinglyLinkedList<Integer> singlyLinkedList = new SinglyLinkedList<Integer> (  );
        singlyLinkedList.addFirst ( 1 );
        singlyLinkedList.addFirst ( 2 );
        singlyLinkedList.addFirst ( 2 );
        singlyLinkedList.addFirst ( 3 );

        singlyLinkedList.displayFisrt ();

        singlyLinkedList.removeFirst ();
        singlyLinkedList.removeFirst ();
        singlyLinkedList.displayFisrt ();
    }

    public Node getFirst() {
        return first;
    }

    public void setFirst(Node first) {
        this.first = first;
    }

    public long getSize() {
        return size;
    }

    private class Node{
        private E element;

        private Node next;

        Node(E element,Node next){
            this.element = element;
            this.next = next;
        }

        public E getElement() {
            return element;
        }

        public void setElement(E element) {
            this.element = element;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }
    }
}
